package com.dog.basics.security.service.impl;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.dog.basics.bean.dto.admin.common.AppConnectBindDto;
import com.dog.basics.common.exception.CustomException;
import com.dog.basics.security.dao.AppConnectMapper;
import com.dog.basics.security.enums.App;
import com.dog.basics.security.model.AppConnect;
import com.dog.basics.security.service.AppConnectService;
import com.dog.basics.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;


/**
 *
 * @author dog on 2018/09/07.
 */
@Service
@AllArgsConstructor
public class AppConnectServiceImpl extends ServiceImpl<AppConnectMapper, AppConnect> implements AppConnectService {

	//private final WxMaService wxMaService;

	/**
	 * DogUserServiceImpl#insertUserIfNecessary 将会清楚该缓存信息
	 * @param bizUserId
	 * @param app
	 * @return
	 */
	@Override
	@Cacheable(cacheNames = "AppConnect", key = "#app.value() + ':' + #bizUserId")
	public AppConnect getByBizUserId(String bizUserId, App app) {
		return this.baseMapper.getByBizUserId(bizUserId, app.value());
	}

	/**
	 * 绑定第三方账户信息
	 * @param dto
	 * @return
	 * guonh 2019年12月21日
	 */
	@Override
	public boolean editBindingThirdPartyAccount(AppConnectBindDto dto) {
		//判断是否什么第三方
		App app = App.valueOf(dto.getAppType());
		if (ObjectUtil.isNull(app)) {
			throw new CustomException("获取不到您绑定什么第三方");
		}
		//获取第三方openId
		String openId = "";
	    if (app.value().equals(App.WX.value())) {
			WxMaJscode2SessionResult session = null;
			try {
				//session = wxMaService.getUserService().getSessionInfo(dto.getCode());
				openId = session.getOpenid();
			} catch (Exception e) {
				throw new CustomException("获取不到第三方账户,请重试");
			}
		}
		//判断此第三方在数据库中是否有对应的用户
		this.baseMapper.selectList(Wrappers.<AppConnect>lambdaQuery().eq(AppConnect::getAppId, app.value())
				.eq(AppConnect::getBizUserId, openId)).forEach(e->this.removeById(e.getId()));
		//判断本账户的第三方是否有
		this.baseMapper.selectList(Wrappers.<AppConnect>lambdaQuery().eq(AppConnect::getUserId, SecurityUtils.getUser().getUserId()).eq(AppConnect::getAppId, app.value())
				).forEach(e->this.removeById(e.getId()));
		//新增或删除第三方账户
		AppConnect appConnect = new AppConnect();
		appConnect.setAppId(app.value());
		appConnect.setUserId(SecurityUtils.getUser().getUserId());
		appConnect.setBizUserId(openId);
		if (Validator.isFalse(this.save(appConnect))) {
			throw new CustomException("绑定第三方失败,请重试");
		}
		return true;
	}

}
